#
# @lc app=leetcode.cn id=529 lang=python3
#
# [529] 扫雷游戏
#

# @lc code=start
class Solution:
    digit = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        row, column = click[0], click[1]
        if row < 0 or column < 0 or row >= len(board) or column >= len(board[row]):
            assert False
            return board

        if board[row][column] == 'M':
            board[row][column] = 'X'
            return board
        
        self.dfs(row, column, board)
        return board
        
    def dfs(self, row: int, column: int, board: List[List[str]]):
        if row < 0 or column < 0 or row >= len(board) or column >= len(board[row]):
            return
        ## 更新过，不再处理
        if board[row][column] != 'E':
            return
        
        count = self.aroundMineCount(row, column, board)
        if count == 0:
            board[row][column] = 'B'
            for r, c in [(row - 1, column - 1), (row - 1, column), (row - 1, column + 1), (row, column - 1), (row, column + 1), (row + 1, column - 1), (row + 1, column), (row + 1, column + 1)]:
                self.dfs(r, c, board)
        else:
            board[row][column] = self.digit[count]
            
    def aroundMineCount(self, row: int, column: int, board: List[List[str]]) -> int:
        if row < 0 or column < 0 or row >= len(board) or column >= len(board[row]):
            assert False
            return 0

        result = 0
        # 从上到右下个位置
        for r, c in [(row - 1, column - 1), (row - 1, column), (row - 1, column + 1), (row, column - 1), (row, column + 1), (row + 1, column - 1), (row + 1, column), (row + 1, column + 1)]:
            if r < 0 or c < 0 or r >= len(board) or c >= len(board[row]):
                continue
            if board[r][c] == 'M':
                result += 1
        return result
        
# @lc code=end

